<template>
  <div class="register-container">
    <div class="register-box">
      <h2 class="title">加入 Mediotube</h2>
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        @submit.prevent="handleRegister"
      >
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="用户名"
            prefix-icon="User"
          />
        </el-form-item>
        
        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            placeholder="邮箱"
            prefix-icon="Message"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="确认密码"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-button type="primary" class="submit-btn" :loading="loading" @click="handleRegister">
          注册
        </el-button>
      </el-form>
      
      <div class="login-link">
        已有账号？<router-link to="/login">立即登录</router-link>
      </div>
      
      <div class="social-login">
        <p class="divider"><span>或使用以下方式</span></p> <!-- Wrapped span for consistency -->
        <div class="social-buttons">
          <el-button class="social-btn google">
            <el-icon><img src="@/assets/google-icon.svg" alt="Google" /></el-icon> <!-- Corrected path -->
            Google 账号注册
          </el-button>
          <el-button class="social-btn github">
            <el-icon><img src="@/assets/github-icon.svg" alt="GitHub" /></el-icon> <!-- Corrected path -->
            GitHub 账号注册
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Message, Lock } from '@element-plus/icons-vue'

const router = useRouter()

// 表单引用
const registerFormRef = ref(null)

// 加载状态
const loading = ref(false)

// 注册表单
const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: ''
})

// 注册表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, message: '用户名长度不能小于2位', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

import axios from '@/services/axios'

// 处理注册
const handleRegister = async () => {
  // 验证表单
  const form = registerFormRef.value; // 获取表单实例
  if (!form) return;
  try {
    await form.validate(); // 触发验证
  } catch (error) {
    // 验证失败
    return;
  }

  loading.value = true;
  try {
    const response = await axios.post('/api/auth/register', {
      username: registerForm.username,
      email: registerForm.email,
      password: registerForm.password,
    });

    // 注册成功，通常后端会返回 token
    // 可以选择在这里自动登录或提示用户去登录
    // localStorage.setItem('token', response.data.token);

    ElMessage.success('注册成功，请登录');
    router.push('/login');
  } catch (error) {
    let errorMessage = '注册失败，请稍后重试';
    if (error.response && error.response.data) {
      // 尝试获取后端返回的错误信息
      if (error.response.data.errors && error.response.data.errors.length > 0) {
        // 处理 express-validator 的错误数组
        errorMessage = error.response.data.errors.map(err => err.msg).join(', ');
      } else if (error.response.data.error) {
        // 处理自定义的错误消息
        errorMessage = error.response.data.error;
      }
    }
    ElMessage.error(errorMessage);
    console.error('注册失败:', error.response || error);
  } finally {
    loading.value = false;
  }
};


</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #b4e0e7 0%, #dfe4e7 100%);
  background-size: cover;
  background-position: center;
}

.register-box {
  width: 100%;
  max-width: 400px;
  background: linear-gradient(135deg, #b4e0e7 0%, #dfe4e7 100%);
  border-radius: 8px;
  padding: 40px; 
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  margin: auto;
}

.title {
  text-align: center;
  margin-bottom: 30px;
  color: #303133; 
  font-weight: 600;
}

.submit-btn {
  width: 100%;
  padding: 12px;
  font-size: 16px;
  margin-top: 10px; 
  margin-bottom: 20px;
}

.login-link {
  text-align: center;
  font-size: 14px;
  color: #606266;
  margin-bottom: 30px;
}

.login-link a {
  color: #409eff;
  text-decoration: none;
}

.login-link a:hover {
  color: #79bbff;
  text-decoration: underline;
}

.social-login {
  margin-top: 30px;
}

.divider {
  display: flex;
  align-items: center;
  text-align: center;
  color: #909399;
  font-size: 14px;
  margin-bottom: 20px;
}

.divider::before,
.divider::after {
  content: '';
  flex: 1;
  border-bottom: 1px solid #e4e7ed;
}

.divider span {
  padding: 0 10px;
}

.social-buttons {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.social-btn {
  width: 100%;
  padding: 10px;
  font-size: 14px;
  justify-content: center;
}

.social-btn .el-icon {
  margin-right: 8px;
  font-size: 18px;
  display: inline-flex;
  align-items: center;
}

.social-btn img {
  width: 18px;
  height: 18px;
}

/* Ensure prefix icons are aligned */
:deep(.el-input__prefix) {
    display: inline-flex;
    align-items: center;
}

</style>